package cn.bdqn.service;

import cn.bdqn.mapper.ItemKillMapper;
import cn.bdqn.mapper.ItemKillSuccessMapper;
import cn.bdqn.pojo.ItemKillSuccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 定时任务服务，需要定时任务做什么事情，就写在这个类中
 */
@Service
public class QuartzService {

    private static final Logger log = LoggerFactory.getLogger(QuartzService.class);


    @Resource
    private ItemKillSuccessMapper itemKillSuccessMapper;

    @Resource
    private ItemKillMapper itemKillMapper;

    @Scheduled(cron = "0/30 * * * * ?")
    public void scanOrderStatus(){
        //查找订单状态为0，并且订单创建时间跟现在的时间对比超过30秒的订单
        List<ItemKillSuccess> itemKillSuccessList = itemKillSuccessMapper.findByStatusAndCreateTime();
        //把所有的订单状态改成-1（失效）,库存+1
        for(ItemKillSuccess itemKillSuccess:itemKillSuccessList){
            //订单还未支付，让订单失效
            ItemKillSuccess ik = new ItemKillSuccess();
            ik.setCode(itemKillSuccess.getCode());
            ik.setStatus(-1);
            int row = itemKillSuccessMapper.updateById(ik);
            log.info("定时任务执行：订单号：{}，已经失效！",itemKillSuccess.getCode());
            if(row>0){
                //订单失效，对应商品的库存+1
                itemKillMapper.updateByIdAdd(itemKillSuccess.getKillId());
            }
        }
    }

}
